package cn.flyinke.jc;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.casbin.jcasbin.main.Enforcer;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.kit.PathKit;

public class JCasbinAuthzInterceptor implements Interceptor {
    static Enforcer enforcer;


    static {
        //enforcer = new Enforcer(PathKit.getRootClassPath()+"/authz_model.conf",PathKit.getRootClassPath()+"/authz_policy.csv");
    	//enforcer = new Enforcer(PathKit.getRootClassPath()+"/authz_model.conf", new FileTestAdapter(PathKit.getRootClassPath()+"/authz_policy.csv"));
    	enforcer = new Enforcer(PathKit.getRootClassPath()+"/authz_model.conf", new JCasbinAdapter());
    }

    private String getUser(Controller ctr) {
    	return ctr.getPara("username");
    }


    public void intercept(Invocation inv) {
        Controller ctr  = inv.getController();
        
        HttpServletRequest request = inv.getController().getRequest();
        HttpServletResponse response = inv.getController().getResponse();

        
        
        String user = getUser(ctr);
        
//        String path = inv.getActionKey();
//        String method = inv.getMethodName();
        
        String path = request.getRequestURI();
        String method = request.getMethod();
        
        System.out.println("(" + user + ", " + path + ", " + method + ")");
        
        if (enforcer.enforce(user, path, method)) {
            inv.invoke();
        } else {
            ctr.renderText("无此权限");
        }
    }
}
